package com.example.pdfrename

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Chronometer
import android.widget.ListView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.TextRecognition
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader
import com.tom_roush.pdfbox.pdmodel.PDDocument
import com.tom_roush.pdfbox.text.PDFTextStripper
import java.util.Calendar

class MainActivity : AppCompatActivity() {
    private val fileSelectRequestCode = 1000

    @RequiresApi(Build.VERSION_CODES.N_MR1)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sdkVersion: Int = android.os.Build.VERSION.SDK_INT
        val model: String = android.os.Build.MODEL
        val brand: String = android.os.Build.BRAND
        val manufacture: String = android.os.Build.MANUFACTURER

        Toast.makeText(
            this,
            brand + "\t" + model + "\t" + sdkVersion.toString(),
            Toast.LENGTH_SHORT
        ).show()
        if (sdkVersion > 31) {
            findViewById<Chronometer>(R.id.chronometer).start()
            val handler = Handler()
            handler.postDelayed({
                // 延迟执行的代码
                val intent = Intent(Intent.ACTION_VIEW)
                intent.setClassName(
                    "com.huawei.works",
                    "com.huawei.works.attendance.ui.activity.MainActivity"
                )
                intent.putExtra("LaunchActivity", "mainActivity")
                intent.putExtra("alias", "mainActivity")
                startActivity(intent)
            }, 60000) // 延迟1秒

            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_MEDIA_IMAGES
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                    fileSelectRequestCode
                )
            }

        }
        val buttonSelectFile: Button = findViewById(R.id.button_select_file_tree)
        buttonSelectFile.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
            intent.apply {
                flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            }
            startActivityForResult(
                Intent.createChooser(intent, "选择文件"),
                fileSelectRequestCode + 1
            )
        }
        val button_dingding: Button = findViewById(R.id.button_dingding)
        button_dingding.setOnClickListener {

            val apps = ArrayList<String>()
            apps.add("com.huawei.works")
            val listView: ListView = findViewById(R.id.listView)
            val adapter =
                ArrayAdapter(this, android.R.layout.simple_list_item_1, apps)
            listView.adapter = adapter
            listView.setOnItemClickListener { parent, view, positionApp, id ->

                val listView: ListView = findViewById(R.id.listView)
                var activities = ArrayList<String>()
                activities.add("com.huawei.works.attendance.ui.activity.MainActivity")
                val adapter =
                    ArrayAdapter(this, android.R.layout.simple_list_item_1, activities)
                listView.adapter = adapter
                listView.setOnItemClickListener { parent, view, position, id ->
                    try {
                        val intent = Intent(Intent.ACTION_VIEW)
                        intent.setClassName(apps.get(positionApp), activities.get(position))
                        intent.putExtra("LaunchActivity", "mainActivity")
                        intent.putExtra("alias", "mainActivity")
                        startActivity(intent)
                    } catch (e: Exception) {
                        Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()

                    }

                }
//                        val dingding = packageManager.getLaunchIntentForPackage(items.get(position))
//
//                        startActivity(dingding)
            }

        }

        val buttonSelectFileTree: Button = findViewById(R.id.button_select_file)
        buttonSelectFileTree.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)

            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*"); // 所有文件类型，可指定如"image/*"或"application/pdf"
            //                intent.setType("application/pdf"); // 所有文件类型，可指定如"image/*"或"application/pdf"
            startActivityForResult(
                Intent.createChooser(intent, "选择目录"),

                fileSelectRequestCode
            )
        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                if (requestCode == fileSelectRequestCode) {
                    val realName = getFileName(uri)
                    if (realName.endsWith("pdf")) {
                        PDFBoxResourceLoader.init(this)
                        val contentResolver = this.contentResolver
                        contentResolver.openInputStream(uri)?.use { input ->
                            val document = PDDocument.load(input)
                            val textStripper = PDFTextStripper()
                            val text = textStripper.getText(document)
                            val items = text.split("\n")
                            val listView: ListView = findViewById(R.id.listView)
                            val adapter =
                                ArrayAdapter(this, android.R.layout.simple_list_item_1, items)
                            listView.adapter = adapter
                        }
                    } else if (false) {


                    } else {
                        val imageUri: Uri? = data.data // 获取图片的Uri
                        val list = ArrayList<String>()

                        val textRecognizer = TextRecognition.getClient(
                            ChineseTextRecognizerOptions.Builder().build()
                        )
                        val image = InputImage.fromFilePath(this, imageUri!!) // 从Uri获取图片

                        val result = textRecognizer.process(image)
                            .addOnSuccessListener { visionText ->
                                // 处理识别结果
                                for (block in visionText.textBlocks) {
                                    val blockText = block.text
                                    list.addAll(blockText.split("\n"))
                                    val listView: ListView = findViewById(R.id.listView)
                                    val adapter = ArrayAdapter(
                                        this,
                                        android.R.layout.simple_list_item_1,
                                        list
                                    )
                                    listView.adapter = adapter
                                    val blockCornerPoints =
                                        block.cornerPoints // 获取文字块的角点坐标，可用于绘制在图像上
                                }
                            }
                            .addOnFailureListener { e ->
                                // 处理错误情况
                                list.add(e.message + "")
                            }


                    }
                } else {
                    val listView: ListView = findViewById(R.id.listView)
                    var list = ArrayList<String>()


                    val selectedFilePath = uri.toString()
                    val pickedDir = DocumentFile.fromTreeUri(this, uri)


                    val size = pickedDir?.listFiles()?.size

//                    val realName = getFileName(uri)
//                    list.add(realName)
                    PDFBoxResourceLoader.init(this)
                    val dic = mutableMapOf<String, String>()
                    for (file: DocumentFile in pickedDir!!.listFiles()) {
                        val realName = getFileName(file.uri)
                        if (realName.endsWith("xml")) {
                            file.delete()
                            continue
                        }
                        try {
                            if (!realName.endsWith("pdf")) {
                                list.add(realName)
                                continue
                            }
                            val uri = file.uri
                            val contentResolver = this.contentResolver

                            contentResolver.openInputStream(uri)?.use { input ->
                                val document = PDDocument.load(input)
                                val textStripper = PDFTextStripper()
                                val text = textStripper.getText(document)
                                if (text.startsWith("高德地图")) {
                                    var city = ""
                                    val city_line = text.split("\n")[5].split(" ")
                                    if (city_line.size > 5) {
                                        city = city_line[5]
                                    } else {
                                        for (line in text.split("\n")) {
                                            for (word in line.split(" ")) {
                                                if (word.endsWith("市") and !word.equals("城市")) {
                                                    city = word
                                                    break
                                                }
                                            }
                                        }
                                    }
                                    val amount_line = text.split("\n")[3]
                                    val amount_index = amount_line.indexOf("合计") + 2
                                    val amount = amount_line.substring(amount_index)
                                    dic.put(
                                        realName,
                                        text.split("\n")[2].split("至")[1].substring(
                                            0,
                                            10
                                        ) + city + "[$amount]"
                                    )
                                } else {
                                }
                            }

                        } catch (e: Exception) {
                            list.add(e.message + "" + realName)
                        }
                    }

                    var amountTotal: Float = 0f
                    for (file: DocumentFile in pickedDir!!.listFiles()) {
                        val realName = getFileName(file.uri)

                        try {
                            if (realName.endsWith("电子发票.pdf")) {
                                val new_name = dic.getOrDefault(
                                    realName.replace(
                                        "电子发票",
                                        "电子行程单"
                                    ), ""
                                ) + "电子发票.pdf"

                                if (realName.equals(new_name)) {
                                } else {
                                    file.renameTo(new_name)
                                }


                            } else if (realName.endsWith("电子行程单.pdf")) {
                                val new_name = dic.getOrDefault(realName, "") + "电子行程单.pdf"
                                var start_index = new_name.indexOf("[")
                                var end_index = new_name.indexOf("]")
                                var amount = new_name.substring(start_index + 1, end_index)
                                var amountNo = amount.replace("元", "").toFloat()
                                amountTotal = amountTotal + amountNo
                                list.add(new_name)


                                if (realName.equals(new_name)) {
                                } else {
                                    file.renameTo(new_name)
                                }
                            }
                        } catch (e: Exception) {
                            list.add(e.message + "" + realName)

                        }

                    }
                    list.add(0, "合计\t" + amountTotal.toString() + "元")
                    val adapter = ArrayAdapter(
                        this,
                        android.R.layout.simple_list_item_1,
                        list.sorted().reversed()
                    )
                    listView.adapter = adapter
                    listView.setOnItemClickListener { parent, view, position, id ->
                        val clickFile = list.sorted().reversed().get(position)
                        Toast.makeText(this, position.toString() + clickFile, Toast.LENGTH_SHORT)
                            .show()
                        // 处理点击事件
                        for (file: DocumentFile in pickedDir!!.listFiles()) {
                            val realName = getFileName(file.uri)
                            if (realName.endsWith(clickFile)) {
                                contentResolver.openInputStream(file.uri)?.use { input ->
                                    val document = PDDocument.load(input)
                                    val textStripper = PDFTextStripper()
                                    val text = textStripper.getText(document)
                                    if (text.startsWith("高德地图")) {

//                                        Toast.makeText(this,text, Toast.LENGTH_SHORT).show()
                                        val builder = AlertDialog.Builder(this)
                                            .setTitle(realName)
                                            .setMessage(text)
                                            .setPositiveButton("确定") { dialog, _ ->
                                                // 点击确定后的逻辑
//                                                Toast.makeText(this, "已删除", Toast.LENGTH_SHORT).show()
                                                dialog.dismiss()
                                            }
//                                            .setNegativeButton("取消") { dialog, _ ->
//                                                dialog.dismiss()
//                                            }
                                        builder.create().show()
                                    } else {
                                    }
                                }
                                break
                            }
                        }
                    }

                }

            }


        }


    }

//


    private fun getFileName(uri: Uri): String {

        val projection = arrayOf<String?>(MediaStore.Images.Media.DISPLAY_NAME)
        val cursor: Cursor? = this.getContentResolver().query(uri, projection, null, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                val column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                val fileName = cursor.getString(column_index)
                cursor.close()
                return fileName!!
            }
            cursor.close()
        }

        return ""
    }


    fun getCurrentDate(): String {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        return "$year-$month-$day"
    }
}